import { useEffect, 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 { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { Save, Loader2, MapPin, ShieldAlert, Languages, Info } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";

interface Props {
  userId: string;
  initial?: {
    bio?: string | null;
    mailing_street?: string | null;
    mailing_city?: string | null;
    mailing_state?: string | null;
    mailing_zip?: string | null;
    emergency_contact_name?: string | null;
    emergency_contact_phone?: string | null;
    preferred_language?: string | null;
  };
}

const LANGUAGES = [
  { value: "en", label: "English" },
  { value: "es", label: "Spanish" },
  { value: "fr", label: "French" },
  { value: "pt", label: "Portuguese" },
  { value: "zh", label: "Chinese" },
];

export default function PersonalDetailsCard({ userId, initial }: Props) {
  const [bio, setBio] = useState("");
  const [street, setStreet] = useState("");
  const [city, setCity] = useState("");
  const [state, setState] = useState("");
  const [zip, setZip] = useState("");
  const [ecName, setEcName] = useState("");
  const [ecPhone, setEcPhone] = useState("");
  const [language, setLanguage] = useState("en");
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!initial) return;
    setBio(initial.bio || "");
    setStreet(initial.mailing_street || "");
    setCity(initial.mailing_city || "");
    setState(initial.mailing_state || "");
    setZip(initial.mailing_zip || "");
    setEcName(initial.emergency_contact_name || "");
    setEcPhone(initial.emergency_contact_phone || "");
    setLanguage(initial.preferred_language || "en");
  }, [initial]);

  const handleSave = async () => {
    if (!userId) return;
    setSaving(true);
    const { error } = await supabase
      .from("profiles")
      .update({
        bio: bio.trim() || null,
        mailing_street: street.trim() || null,
        mailing_city: city.trim() || null,
        mailing_state: state.trim() || null,
        mailing_zip: zip.trim() || null,
        emergency_contact_name: ecName.trim() || null,
        emergency_contact_phone: ecPhone.trim() || null,
        preferred_language: language || "en",
      })
      .eq("user_id", userId);
    setSaving(false);
    if (error) toast.error("Failed to save details");
    else toast.success("Personal details saved");
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-lg flex items-center gap-2">
          <Info className="h-5 w-5 text-primary" /> Personal Details
        </CardTitle>
        <CardDescription>
          Tell us a bit about yourself, your mailing address, and an emergency contact.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-5">
        <div className="space-y-2">
          <Label htmlFor="bio">About You</Label>
          <Textarea
            id="bio"
            value={bio}
            onChange={(e) => setBio(e.target.value)}
            placeholder="A short bio (optional)"
            maxLength={500}
            rows={3}
          />
          <p className="text-xs text-muted-foreground">{bio.length}/500</p>
        </div>

        <Separator />

        <div className="space-y-3">
          <div className="flex items-center gap-2 text-sm font-medium text-foreground">
            <MapPin className="h-4 w-4 text-muted-foreground" /> Mailing Address
          </div>
          <Input
            value={street}
            onChange={(e) => setStreet(e.target.value)}
            placeholder="Street address"
          />
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
            <Input value={city} onChange={(e) => setCity(e.target.value)} placeholder="City" />
            <Input value={state} onChange={(e) => setState(e.target.value)} placeholder="State" />
            <Input value={zip} onChange={(e) => setZip(e.target.value)} placeholder="ZIP" />
          </div>
        </div>

        <Separator />

        <div className="space-y-3">
          <div className="flex items-center gap-2 text-sm font-medium text-foreground">
            <ShieldAlert className="h-4 w-4 text-muted-foreground" /> Emergency Contact
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            <Input
              value={ecName}
              onChange={(e) => setEcName(e.target.value)}
              placeholder="Contact name"
            />
            <Input
              value={ecPhone}
              onChange={(e) => setEcPhone(e.target.value)}
              placeholder="Contact phone"
            />
          </div>
        </div>

        <Separator />

        <div className="space-y-2">
          <Label htmlFor="lang" className="flex items-center gap-2">
            <Languages className="h-4 w-4 text-muted-foreground" /> Preferred Language
          </Label>
          <select
            id="lang"
            value={language}
            onChange={(e) => setLanguage(e.target.value)}
            className="w-full md:w-64 h-10 rounded-md border border-input bg-background px-3 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
          >
            {LANGUAGES.map((l) => (
              <option key={l.value} value={l.value}>
                {l.label}
              </option>
            ))}
          </select>
        </div>

        <div className="flex justify-end">
          <Button onClick={handleSave} disabled={saving} className="gap-2">
            {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
            {saving ? "Saving…" : "Save Details"}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
