import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { CheckCircle2, Loader2, Building2, AlertTriangle, Lock } from "lucide-react";

export default function VendorProfileSubmitPage() {
  const { token } = useParams<{ token: string }>();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [vendor, setVendor] = useState<{ vendor_id: string; vendor_name: string } | null>(null);

  // Form state
  const [remittanceAddress, setRemittanceAddress] = useState("");
  const [taxId, setTaxId] = useState("");
  const [is1099, setIs1099] = useState(false);
  const [w9File, setW9File] = useState<File | null>(null);

  const [carrier, setCarrier] = useState("");
  const [policyNumber, setPolicyNumber] = useState("");
  const [expirationDate, setExpirationDate] = useState("");
  const [coiFile, setCoiFile] = useState<File | null>(null);

  const [bankName, setBankName] = useState("");
  const [accountHolder, setAccountHolder] = useState("");
  const [routingNumber, setRoutingNumber] = useState("");
  const [accountNumber, setAccountNumber] = useState("");
  const [accountType, setAccountType] = useState("checking");

  useEffect(() => {
    if (!token) return;
    (async () => {
      setLoading(true);
      const { data, error } = await supabase.rpc("lookup_vendor_profile_request", { p_token: token });
      if (error || !data || data.length === 0) {
        setError("This link is invalid or could not be found.");
        setLoading(false);
        return;
      }
      const row = data[0];
      if (row.submitted_at) {
        setError("This information has already been submitted. If you need to update it, please contact us.");
      } else if (new Date(row.expires_at) < new Date()) {
        setError("This link has expired. Please contact us to request a new submission link.");
      } else {
        setVendor({ vendor_id: row.vendor_id, vendor_name: row.vendor_name });
      }
      setLoading(false);
    })();
  }, [token]);

  const uploadFile = async (file: File, prefix: string): Promise<string | null> => {
    if (!vendor) return null;
    const ext = file.name.split(".").pop() || "pdf";
    const path = `vendor-profile/${vendor.vendor_id}/${prefix}-${Date.now()}.${ext}`;
    const { error: upErr } = await supabase.storage
      .from("public-form-attachments")
      .upload(path, file, { upsert: false });
    if (upErr) throw upErr;
    const { data: pub } = supabase.storage.from("public-form-attachments").getPublicUrl(path);
    return pub.publicUrl;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!token || !vendor) return;
    if (!remittanceAddress.trim() || !taxId.trim()) {
      setError("Remittance address and Tax ID are required.");
      return;
    }
    setSubmitting(true);
    setError(null);

    try {
      let w9Url: string | null = null;
      let coiUrl: string | null = null;
      if (w9File) w9Url = await uploadFile(w9File, "w9");
      if (coiFile) coiUrl = await uploadFile(coiFile, "coi");

      const { data, error: rpcErr } = await supabase.rpc("submit_vendor_profile", {
        p_token: token,
        p_remittance_address: remittanceAddress.trim(),
        p_tax_id: taxId.trim(),
        p_is_1099_eligible: is1099,
        p_w9_document_url: w9Url,
        p_insurance_carrier: carrier.trim() || null,
        p_insurance_policy_number: policyNumber.trim() || null,
        p_insurance_expiration_date: expirationDate || null,
        p_insurance_document_url: coiUrl,
        p_ach_bank_name: bankName.trim() || null,
        p_ach_account_holder: accountHolder.trim() || null,
        p_ach_routing_number: routingNumber.trim() || null,
        p_ach_account_number: accountNumber.trim() || null,
        p_ach_account_type: bankName.trim() ? accountType : null,
      });

      if (rpcErr || data === false) {
        setError("Submission failed. The link may have expired. Please contact us.");
      } else {
        setSubmitted(true);
      }
    } catch (err: any) {
      setError("Could not upload document: " + (err?.message || "Unknown error"));
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-muted/20">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (submitted) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-muted/20 p-4">
        <Card className="max-w-md w-full">
          <CardContent className="p-8 text-center space-y-4">
            <CheckCircle2 className="h-16 w-16 text-emerald-600 mx-auto" />
            <h2 className="text-2xl font-bold">Thank you!</h2>
            <p className="text-muted-foreground">
              Your vendor profile information has been received and your record has been updated.
            </p>
          </CardContent>
        </Card>
      </div>
    );
  }

  if (error && !vendor) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-muted/20 p-4">
        <Card className="max-w-md w-full">
          <CardContent className="p-8 text-center space-y-4">
            <AlertTriangle className="h-12 w-12 text-destructive mx-auto" />
            <h2 className="text-xl font-bold">Unable to submit</h2>
            <p className="text-muted-foreground">{error}</p>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-muted/20 py-10 px-4">
      <div className="max-w-2xl mx-auto">
        <Card>
          <CardHeader>
            <div className="flex items-center gap-3">
              <Building2 className="h-8 w-8 text-primary" />
              <div>
                <CardTitle>Vendor Profile Update</CardTitle>
                <CardDescription>
                  {vendor?.vendor_name ? `For: ${vendor.vendor_name}` : "Vendor profile"}
                </CardDescription>
              </div>
            </div>
            <p className="text-xs text-muted-foreground flex items-center gap-1 mt-2">
              <Lock className="h-3 w-3" /> This is a secure, encrypted submission.
            </p>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-8">
              {/* Remittance & Tax */}
              <section className="space-y-4">
                <h3 className="font-semibold text-base">Payment Remittance & Tax</h3>
                <div>
                  <Label htmlFor="remit">Remittance Address *</Label>
                  <Textarea
                    id="remit"
                    value={remittanceAddress}
                    onChange={(e) => setRemittanceAddress(e.target.value)}
                    placeholder="Street, City, State ZIP"
                    rows={3}
                    required
                  />
                </div>
                <div>
                  <Label htmlFor="tax">Tax ID (EIN or SSN) *</Label>
                  <Input
                    id="tax"
                    value={taxId}
                    onChange={(e) => setTaxId(e.target.value)}
                    placeholder="XX-XXXXXXX"
                    required
                  />
                </div>
                <div className="flex items-center gap-2">
                  <Checkbox
                    id="is1099"
                    checked={is1099}
                    onCheckedChange={(v) => setIs1099(v === true)}
                  />
                  <Label htmlFor="is1099" className="cursor-pointer font-normal">
                    I am 1099 eligible (will receive a 1099-NEC for services rendered)
                  </Label>
                </div>
                <div>
                  <Label htmlFor="w9">W-9 Form (optional)</Label>
                  <Input
                    id="w9"
                    type="file"
                    accept=".pdf,.png,.jpg,.jpeg"
                    onChange={(e) => setW9File(e.target.files?.[0] || null)}
                  />
                </div>
              </section>

              {/* Insurance */}
              <section className="space-y-4">
                <h3 className="font-semibold text-base">Insurance Information</h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="carrier">Insurance Carrier</Label>
                    <Input id="carrier" value={carrier} onChange={(e) => setCarrier(e.target.value)} />
                  </div>
                  <div>
                    <Label htmlFor="policy">Policy Number</Label>
                    <Input id="policy" value={policyNumber} onChange={(e) => setPolicyNumber(e.target.value)} />
                  </div>
                  <div>
                    <Label htmlFor="exp">Expiration Date</Label>
                    <Input id="exp" type="date" value={expirationDate} onChange={(e) => setExpirationDate(e.target.value)} />
                  </div>
                  <div>
                    <Label htmlFor="coi">Certificate of Insurance</Label>
                    <Input
                      id="coi"
                      type="file"
                      accept=".pdf,.png,.jpg,.jpeg"
                      onChange={(e) => setCoiFile(e.target.files?.[0] || null)}
                    />
                  </div>
                </div>
              </section>

              {/* ACH */}
              <section className="space-y-4">
                <h3 className="font-semibold text-base">Direct Deposit (ACH) — Optional</h3>
                <p className="text-xs text-muted-foreground">
                  Provide bank details to receive payments via ACH instead of check.
                </p>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="bank">Bank Name</Label>
                    <Input id="bank" value={bankName} onChange={(e) => setBankName(e.target.value)} />
                  </div>
                  <div>
                    <Label htmlFor="holder">Account Holder Name</Label>
                    <Input id="holder" value={accountHolder} onChange={(e) => setAccountHolder(e.target.value)} />
                  </div>
                  <div>
                    <Label htmlFor="routing">Routing Number (9 digits)</Label>
                    <Input
                      id="routing"
                      value={routingNumber}
                      onChange={(e) => setRoutingNumber(e.target.value.replace(/\D/g, "").slice(0, 9))}
                      inputMode="numeric"
                    />
                  </div>
                  <div>
                    <Label htmlFor="acct">Account Number</Label>
                    <Input
                      id="acct"
                      value={accountNumber}
                      onChange={(e) => setAccountNumber(e.target.value.replace(/\D/g, "").slice(0, 17))}
                      inputMode="numeric"
                    />
                  </div>
                  <div>
                    <Label htmlFor="atype">Account Type</Label>
                    <Select value={accountType} onValueChange={setAccountType}>
                      <SelectTrigger id="atype"><SelectValue /></SelectTrigger>
                      <SelectContent>
                        <SelectItem value="checking">Checking</SelectItem>
                        <SelectItem value="savings">Savings</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </section>

              {error && <p className="text-sm text-destructive">{error}</p>}

              <Button type="submit" className="w-full" disabled={submitting}>
                {submitting ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null}
                Submit Vendor Profile
              </Button>
            </form>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
