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 { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { CheckCircle2, Loader2, ShieldCheck, AlertTriangle } from "lucide-react";

export default function VendorInsuranceSubmitPage() {
  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 [carrier, setCarrier] = useState("");
  const [policyNumber, setPolicyNumber] = useState("");
  const [expirationDate, setExpirationDate] = useState("");
  const [docFile, setDocFile] = useState<File | null>(null);

  useEffect(() => {
    if (!token) return;
    (async () => {
      setLoading(true);
      const { data, error } = await supabase.rpc("lookup_vendor_insurance_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 insurance 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 handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!token || !vendor) return;
    if (!carrier.trim() || !policyNumber.trim() || !expirationDate) {
      setError("Please complete all required fields.");
      return;
    }
    setSubmitting(true);
    setError(null);

    let documentUrl: string | null = null;
    if (docFile) {
      const ext = docFile.name.split(".").pop() || "pdf";
      const path = `vendor-insurance/${vendor.vendor_id}/${Date.now()}.${ext}`;
      const { error: upErr } = await supabase.storage
        .from("public-form-attachments")
        .upload(path, docFile, { upsert: false });
      if (upErr) {
        setError("Could not upload document: " + upErr.message);
        setSubmitting(false);
        return;
      }
      const { data: pub } = supabase.storage.from("public-form-attachments").getPublicUrl(path);
      documentUrl = pub.publicUrl;
    }

    const { data, error: rpcErr } = await supabase.rpc("submit_vendor_insurance", {
      p_token: token,
      p_carrier: carrier.trim(),
      p_policy_number: policyNumber.trim(),
      p_expiration_date: expirationDate,
      p_document_url: documentUrl,
    });

    setSubmitting(false);
    if (rpcErr || data === false) {
      setError("Submission failed. The link may have expired. Please contact us.");
      return;
    }
    setSubmitted(true);
  };

  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 insurance 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-xl mx-auto">
        <Card>
          <CardHeader>
            <div className="flex items-center gap-3">
              <ShieldCheck className="h-8 w-8 text-primary" />
              <div>
                <CardTitle>Submit Insurance Information</CardTitle>
                <CardDescription>
                  {vendor?.vendor_name ? `For: ${vendor.vendor_name}` : "Vendor insurance update"}
                </CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div>
                <Label htmlFor="carrier">Insurance Carrier *</Label>
                <Input
                  id="carrier"
                  value={carrier}
                  onChange={(e) => setCarrier(e.target.value)}
                  placeholder="e.g. State Farm, Liberty Mutual"
                  required
                />
              </div>
              <div>
                <Label htmlFor="policy">Policy Number *</Label>
                <Input
                  id="policy"
                  value={policyNumber}
                  onChange={(e) => setPolicyNumber(e.target.value)}
                  required
                />
              </div>
              <div>
                <Label htmlFor="exp">Expiration Date *</Label>
                <Input
                  id="exp"
                  type="date"
                  value={expirationDate}
                  onChange={(e) => setExpirationDate(e.target.value)}
                  required
                />
              </div>
              <div>
                <Label htmlFor="doc">Certificate of Insurance (optional)</Label>
                <Input
                  id="doc"
                  type="file"
                  accept=".pdf,.png,.jpg,.jpeg"
                  onChange={(e) => setDocFile(e.target.files?.[0] || null)}
                />
                <p className="text-xs text-muted-foreground mt-1">PDF or image, up to 10MB.</p>
              </div>
              {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 Insurance Information
              </Button>
            </form>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
