import { useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Loader2, Store, ExternalLink, CheckCircle2, AlertCircle, Shield } from "lucide-react";
import { API_URL } from "@/lib/config";
import { PhoneNumberSelector } from "./PhoneNumberSelector";

interface ShopifyConnectProps {
  onClose?: () => void;
}

export function ShopifyConnect({ onClose }: ShopifyConnectProps) {
  const [shopDomain, setShopDomain] = useState("");
  const [phoneNumberId, setPhoneNumberId] = useState("");
  const [isConnecting, setIsConnecting] = useState(false);
  const [error, setError] = useState("");
  const [phoneNumberError, setPhoneNumberError] = useState("");
  const [success, setSuccess] = useState(false);

  const handleConnect = async () => {
    setError("");
    setPhoneNumberError("");
    setSuccess(false);

    // Validate shop domain
    if (!shopDomain.trim()) {
      setError("Please enter your Shopify store domain");
      return;
    }

    // Validate phone number
    if (!phoneNumberId) {
      setPhoneNumberError("Please select a phone number for this store");
      setError("Please select a phone number before connecting");
      return;
    }

    // Normalize domain
    let normalizedDomain = shopDomain.trim().toLowerCase();

    // Remove protocol if present
    normalizedDomain = normalizedDomain.replace(/^https?:\/\//, "");

    // Remove trailing slash
    normalizedDomain = normalizedDomain.replace(/\/$/, "");

    // Add .myshopify.com if not present
    if (!normalizedDomain.includes('.myshopify.com')) {
      // Remove any existing domain extension
      normalizedDomain = normalizedDomain.split('.')[0];
      normalizedDomain = `${normalizedDomain}.myshopify.com`;
    }

    // Validate format
    const shopPattern = /^[a-zA-Z0-9][a-zA-Z0-9-]*\.myshopify\.com$/;
    if (!shopPattern.test(normalizedDomain)) {
      setError("Please enter a valid Shopify domain (e.g., your-store.myshopify.com)");
      return;
    }

    setIsConnecting(true);

    try {
      // Get auth token
      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) {
        setError("Authentication required. Please log in again.");
        setIsConnecting(false);
        return;
      }

      const session = JSON.parse(sessionData);

      // Call the OAuth initiation Edge Function with phoneNumberId
      const response = await fetch(
        `${API_URL}/oauth-shopify?action=init&shop=${encodeURIComponent(normalizedDomain)}&phoneNumberId=${encodeURIComponent(phoneNumberId)}`,
        {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${session.session.access_token}`,
            'Content-Type': 'application/json'
          }
        }
      );

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to initiate OAuth flow');
      }

      const data = await response.json();

      if (data.success && data.authUrl) {
        // Redirect to Shopify for authorization
        setSuccess(true);
        setTimeout(() => {
          window.location.href = data.authUrl;
        }, 1000);
      } else {
        throw new Error('Invalid response from server');
      }

    } catch (err) {
      console.error("Connection error:", err);
      setError(err instanceof Error ? err.message : "Failed to connect to Shopify. Please try again.");
      setIsConnecting(false);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !isConnecting) {
      handleConnect();
    }
  };

  return (
    <Card className="bg-slate-800 border-slate-700 max-w-2xl mx-auto shadow-none border-0">
      <CardHeader>
        <div className="flex items-center gap-3">
          <Store className="w-8 h-8 text-green-500" />
          <div>
            <CardTitle className="text-white text-2xl">Connect Shopify Store</CardTitle>
            <CardDescription className="text-slate-400">
              Link your Shopify shop to enable AI-powered customer support
            </CardDescription>
          </div>
        </div>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* Success Message */}
        {success && (
          <Alert className="bg-green-500/10 border-green-500/50">
            <CheckCircle2 className="h-4 w-4 text-green-500" />
            <AlertDescription className="text-green-500">
              Redirecting to Shopify for authorization...
            </AlertDescription>
          </Alert>
        )}

        {/* Error Message */}
        {error && (
          <Alert className="bg-red-500/10 border-red-500/50">
            <AlertCircle className="h-4 w-4 text-red-500" />
            <AlertDescription className="text-red-500">
              {error}
            </AlertDescription>
          </Alert>
        )}

        {/* Connection Form */}
        <div className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="shopDomain" className="text-white">
              Shopify Store Domain
            </Label>
            <Input
              id="shopDomain"
              type="text"
              placeholder="your-store.myshopify.com"
              value={shopDomain}
              onChange={(e) => setShopDomain(e.target.value)}
              onKeyPress={handleKeyPress}
              className="bg-slate-700 border-slate-600 text-white placeholder:text-slate-400"
              disabled={isConnecting}
            />
            <p className="text-sm text-slate-400">
              Enter your Shopify store domain (e.g., your-store.myshopify.com)
            </p>
          </div>

          <PhoneNumberSelector
            value={phoneNumberId}
            onChange={setPhoneNumberId}
            disabled={isConnecting}
            error={phoneNumberError}
          />

          <Button
            onClick={handleConnect}
            disabled={isConnecting}
            className="w-full bg-green-500 hover:bg-green-600 text-white"
          >
            {isConnecting ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Connecting...
              </>
            ) : (
              <>
                <Store className="w-4 h-4 mr-2" />
                Connect to Shopify
              </>
            )}
          </Button>
        </div>

        {/* Information Section */}
        <div className="bg-slate-700/50 rounded-lg p-4 space-y-3">
          <h4 className="text-white font-medium flex items-center gap-2">
            <ExternalLink className="w-4 h-4 text-green-500" />
            What happens next?
          </h4>
          <ul className="space-y-2 text-sm text-slate-300">
            <li className="flex items-start gap-2">
              <span className="text-green-500 mt-0.5">1.</span>
              <span>You'll be redirected to your Shopify admin panel</span>
            </li>
            <li className="flex items-start gap-2">
              <span className="text-green-500 mt-0.5">2.</span>
              <span>Review the requested permissions and approve the app</span>
            </li>
            <li className="flex items-start gap-2">
              <span className="text-green-500 mt-0.5">3.</span>
              <span>Shopify will securely authorize ShopCall.ai</span>
            </li>
            <li className="flex items-start gap-2">
              <span className="text-green-500 mt-0.5">4.</span>
              <span>Return to ShopCall.ai to complete your setup</span>
            </li>
          </ul>
        </div>

        {/* Security Notice */}
        <div className="bg-blue-500/10 border border-blue-500/50 rounded-lg p-4 space-y-2">
          <div className="flex items-start gap-2">
            <Shield className="w-5 h-5 text-blue-500 mt-0.5 flex-shrink-0" />
            <div className="space-y-1">
              <h4 className="text-white font-medium">Secure & GDPR Compliant</h4>
              <p className="text-sm text-slate-300">
                ShopCall.ai uses Shopify OAuth 2.0 with HMAC verification for maximum security.
                Your credentials are encrypted and stored securely. We comply with all GDPR
                requirements including customer data requests and deletion.
              </p>
            </div>
          </div>
        </div>

        {/* Required Permissions */}
        <div className="bg-slate-700/50 rounded-lg p-4 space-y-3">
          <h4 className="text-white font-medium">Required Permissions (Read-only)</h4>
          <div className="grid grid-cols-2 gap-2 text-sm text-slate-300">
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4 text-green-500" />
              <span>Read Products</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4 text-green-500" />
              <span>Read Orders</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4 text-green-500" />
              <span>Read Customers</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4 text-green-500" />
              <span>Read Inventory</span>
            </div>
            <div className="flex items-center gap-2">
              <CheckCircle2 className="w-4 h-4 text-green-500" />
              <span>Read Price Rules</span>
            </div>
          </div>
          <p className="text-xs text-slate-400">
            These read-only permissions allow our AI to access your store data and provide accurate,
            personalized customer support without modifying anything.
          </p>
        </div>

        {/* GDPR Notice */}
        <div className="bg-green-500/10 border border-green-500/50 rounded-lg p-4 space-y-2">
          <div className="flex items-start gap-2">
            <CheckCircle2 className="w-5 h-5 text-green-500 mt-0.5 flex-shrink-0" />
            <div className="space-y-1">
              <h4 className="text-white font-medium">GDPR & Shopify App Store Ready</h4>
              <p className="text-sm text-slate-300">
                Our integration includes mandatory GDPR webhooks for customer data requests,
                customer data deletion, and shop data deletion. Fully compliant with Shopify
                App Store requirements.
              </p>
            </div>
          </div>
        </div>

        {/* Cancel Button */}
        {onClose && (
          <Button
            variant="outline"
            onClick={onClose}
            className="w-full border-slate-600 text-slate-300 hover:bg-slate-700"
            disabled={isConnecting}
          >
            Cancel
          </Button>
        )}
      </CardContent>
    </Card>
  );
}
