import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
  CardFooter,
} from "@/components/ui/card";
import { SelectionItem } from "@/lib/definitions";

interface VCardFormProps {
  selection: SelectionItem[];
  onValueChange: (field: string, value: string) => void;
  sectionChange: (section: string) => void;
  onGenerate: any;
}

export default function VCardForm({
  selection,
  onValueChange,
  sectionChange,
  onGenerate,
}: VCardFormProps) {
  function generateVCardText(fields: SelectionItem[]) {
    const vcard = [];
    const getValue = (name: string) =>
      fields.find((f) => f.field === name)?.value?.trim() || "";

    // Hilfsfelder sammeln
    const firstName = getValue("Vorname");
    const lastName = getValue("Nachname");
    const nickname = getValue("Spitzname");
    const emailHome = getValue("Email (Privat)");
    const emailWork = getValue("Email (Arbeit)");
    const telHome = getValue("Telefonnummer (Zuhause)");
    const telMobile = getValue("Telefonnummer (Mobile)");
    const telWork = getValue("Telefonnummer (Arbeit)");
    const country = getValue("Land");
    const city = getValue("Ort");
    const street = getValue("Straße");
    const zip = getValue("Postleitzahl");
    const bday = getValue("Geburtstag");
    const org = getValue("Firma");
    const department = getValue("Abteilung");
    const title = getValue("Berufsbezeichnung");
    const role = getValue("Rolle im Unternehmen");
    const url = getValue("Homepage/Persönliche Webseite");
    const note = getValue("Notizen");

    // Start vCard
    vcard.push("BEGIN:VCARD");
    vcard.push("VERSION:3.0");

    // N (strukturierter Name)
    if (firstName || lastName) {
      vcard.push(`N:${lastName};${firstName};;;`);
      vcard.push(`FN:${firstName} ${lastName}`.trim());
    }

    // Spitzname
    if (nickname) vcard.push(`NICKNAME:${nickname}`);

    // Email
    if (emailHome) vcard.push(`EMAIL;TYPE=HOME:${emailHome}`);
    if (emailWork) vcard.push(`EMAIL;TYPE=WORK:${emailWork}`);

    // Telefonnummer
    if (telHome) vcard.push(`TEL;TYPE=HOME:${telHome}`);
    if (telMobile) vcard.push(`TEL;TYPE=CELL:${telMobile}`);
    if (telWork) vcard.push(`TEL;TYPE=WORK:${telWork}`);

    // Geburtstag
    if (bday) vcard.push(`BDAY:${bday}`);

    // Organisation
    if (org || department)
      vcard.push(`ORG:${org}${department ? ";" + department : ""}`);

    // Berufsbezeichnung
    if (title) vcard.push(`TITLE:${title}`);

    // Rolle
    if (role) vcard.push(`ROLE:${role}`);

    // URL
    if (url) vcard.push(`URL:${url}`);

    // Adresse
    if (street || city || zip || country) {
      vcard.push(`ADR:;;${street};${city};;${zip};${country}`);
    }

    // Notizen
    if (note) vcard.push(`NOTE:${note}`);

    // Ende der vCard
    vcard.push("END:VCARD");

    // Rückgabe
    return vcard.join("\r\n");
  }
  const handleGenerate = () => {
    const text = generateVCardText(selection);
    onGenerate(text);
    sectionChange("export");
  };
  return (
    <Card className="w-[600] mx-5">
      <CardHeader>
        <CardTitle>VCard Daten eingeben</CardTitle>
        <CardDescription>
          Alle Eingaben werden ausschließlich lokal im Browser verarbeitet.
          <br /> Es werden keine Daten an den Server gesendet.
          <br />
          (*) Felder sind pflicht!
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form className="space-y-4">
          {/* Loop trough selection and if field is required add a (*) */}
          {selection.map((item) => (
            <div key={item.field} className="space-y-2">
              <label className="text-sm font-medium">
                {item.field}
                {item.required ? (
                  <span className="text-red-500 ml-1">*</span>
                ) : null}
              </label>
              <Input
                placeholder={item.placeholder}
                value={item.value}
                onChange={(e: any) => onValueChange(item.field, e.target.value)}
                required={item.required}
              />
            </div>
          ))}
        </form>
      </CardContent>
      <CardFooter className="flex justify-end">
        <Button
          onClick={handleGenerate}
          disabled={
            !selection
              .find((i) => i.field.toLowerCase() === "vorname")
              ?.value.trim() ||
            !selection
              .find((i) => i.field.toLowerCase() === "nachname")
              ?.value.trim()
          }
        >
          Generieren
        </Button>
      </CardFooter>
    </Card>
  );
}
