"use client";

import React, { useState } from "react";
import { useRouter } from "next/navigation";
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 { Shield, Loader2, CheckCircle2, AlertCircle, PenTool } from "lucide-react";
import { useToast } from "@/components/ui/toast";

interface NDAFormProps {
  dealAddress?: string;
  onSigned?: () => void;
}

export function NDAForm({ dealAddress = "Property Address", onSigned }: NDAFormProps) {
  const router = useRouter();
  const { addToast } = useToast();
  const [loading, setLoading] = useState(false);
  const [signed, setSigned] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    company: "",
    signature: "",
    agreed: false,
  });

  const validate = () => {
    const e: Record<string, string> = {};
    if (!formData.name.trim()) e.name = "Full legal name is required";
    if (!formData.email.trim()) e.email = "Email is required";
    if (!formData.email.includes("@")) e.email = "Valid email is required";
    if (!formData.signature.trim()) e.signature = "Please type your signature";
    if (!formData.agreed) e.agreed = "You must agree to the terms";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) {
      addToast({ type: "error", title: "Please complete all required fields" });
      return;
    }
    setLoading(true);
    await new Promise((resolve) => setTimeout(resolve, 1500));
    setSigned(true);
    setLoading(false);
    addToast({
      type: "success",
      title: "NDA Signed Successfully!",
      description: `You now have access to deal materials for ${dealAddress}.`,
      duration: 6000,
    });
    onSigned?.();
  };

  const fieldError = (field: string) =>
    errors[field] ? (
      <p className="flex items-center gap-1 text-xs text-red-600 mt-1">
        <AlertCircle className="h-3 w-3" />
        {errors[field]}
      </p>
    ) : null;

  if (signed) {
    return (
      <Card className="animate-scale-in">
        <CardContent className="py-12 text-center">
          <div className="flex justify-center mb-4">
            <div className="flex h-16 w-16 items-center justify-center rounded-full bg-emerald-50">
              <CheckCircle2 className="h-8 w-8 text-emerald-500" />
            </div>
          </div>
          <h3 className="text-xl font-semibold text-navy-900 mb-2">NDA Signed Successfully</h3>
          <p className="text-sm text-navy-500 max-w-md mx-auto mb-6">
            Your confidentiality agreement has been recorded. You now have access to the 
            full deal materials for {dealAddress}.
          </p>
          <div className="bg-navy-50 rounded-lg p-4 max-w-sm mx-auto">
            <p className="text-xs text-navy-400 mb-1">Digital Signature</p>
            <p className="text-lg font-semibold text-navy-800" style={{ fontFamily: "'Segoe Script', 'Brush Script MT', cursive" }}>
              {formData.signature}
            </p>
            <p className="text-xs text-navy-400 mt-2">
              Signed on {new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" })} at {new Date().toLocaleTimeString()}
            </p>
          </div>
          <Button variant="gold" className="mt-6 active:scale-[0.98]" onClick={() => router.push("/portal/deals")}>
            View Deal Materials
          </Button>
        </CardContent>
      </Card>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="animate-page-in">
      <Card>
        <CardHeader>
          <div className="flex items-center gap-2 mb-2">
            <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-navy-800">
              <Shield className="h-5 w-5 text-gold-400" />
            </div>
            <div>
              <CardTitle className="text-lg">Confidentiality Agreement</CardTitle>
              <CardDescription className="text-xs">
                Property: <strong>{dealAddress}</strong>
              </CardDescription>
            </div>
          </div>
        </CardHeader>
        <CardContent className="space-y-5">
          {/* NDA Text */}
          <div className="bg-navy-50 rounded-lg p-4 max-h-48 overflow-y-auto text-xs text-navy-700 leading-relaxed space-y-2 border border-navy-100">
            <p className="font-bold text-navy-800 text-sm">CONFIDENTIALITY AND NON-DISCLOSURE AGREEMENT</p>
            <p>
              The undersigned (&ldquo;Recipient&rdquo;) hereby agrees that all information, documents, 
              and materials provided regarding the property located at {dealAddress} 
              (&ldquo;Confidential Information&rdquo;) shall be kept strictly confidential.
            </p>
            <p>
              Recipient agrees to: (1) use the Confidential Information solely for the purpose 
              of evaluating a potential acquisition of the Property; (2) not disclose any 
              Confidential Information to any third party without prior written consent; 
              (3) not copy or reproduce any Confidential Information except as reasonably 
              necessary for evaluation purposes; (4) return or destroy all Confidential 
              Information upon request.
            </p>
            <p>
              This agreement shall remain in effect for a period of two (2) years from the 
              date of execution. Recipient acknowledges that any breach may result in 
              irreparable harm for which monetary damages would be inadequate.
            </p>
            <p>
              By signing below, Recipient acknowledges having read, understood, and agreed 
              to the terms of this Confidentiality and Non-Disclosure Agreement.
            </p>
          </div>

          {/* Form fields */}
          <div>
            <h4 className="text-sm font-semibold text-navy-700 mb-3">Signer Information</h4>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="nda-name">Full Legal Name *</Label>
                <Input
                  id="nda-name"
                  placeholder="John Smith"
                  value={formData.name}
                  onChange={(e) => { setFormData((p) => ({ ...p, name: e.target.value })); if (errors.name) setErrors((p) => { const n = {...p}; delete n.name; return n; }); }}
                  className={`mt-1.5 ${errors.name ? "border-red-400" : ""}`}
                />
                {fieldError("name")}
              </div>
              <div>
                <Label htmlFor="nda-company">Company</Label>
                <Input
                  id="nda-company"
                  placeholder="Smith Capital Group"
                  value={formData.company}
                  onChange={(e) => setFormData((p) => ({ ...p, company: e.target.value }))}
                  className="mt-1.5"
                />
              </div>
            </div>
          </div>

          <div>
            <Label htmlFor="nda-email">Email *</Label>
            <Input
              id="nda-email"
              type="email"
              placeholder="john@smithcapital.com"
              value={formData.email}
              onChange={(e) => { setFormData((p) => ({ ...p, email: e.target.value })); if (errors.email) setErrors((p) => { const n = {...p}; delete n.email; return n; }); }}
              className={`mt-1.5 ${errors.email ? "border-red-400" : ""}`}
            />
            {fieldError("email")}
          </div>

          {/* Signature input */}
          <div>
            <Label className="flex items-center gap-2 mb-2">
              <PenTool className="h-4 w-4 text-navy-500" />
              Type Your Signature *
            </Label>
            <div className="relative">
              <Input
                placeholder="Type your full legal name as signature"
                value={formData.signature}
                onChange={(e) => { setFormData((p) => ({ ...p, signature: e.target.value })); if (errors.signature) setErrors((p) => { const n = {...p}; delete n.signature; return n; }); }}
                className={`text-lg h-14 ${errors.signature ? "border-red-400" : ""}`}
                style={{ fontFamily: "'Segoe Script', 'Brush Script MT', cursive" }}
              />
              {formData.signature && (
                <div className="mt-2 p-3 rounded-lg bg-navy-50 border border-navy-100">
                  <p className="text-xs text-navy-400 mb-1">Signature Preview</p>
                  <p className="text-2xl text-navy-800" style={{ fontFamily: "'Segoe Script', 'Brush Script MT', cursive" }}>
                    {formData.signature}
                  </p>
                  <div className="border-b-2 border-navy-300 mt-1" />
                </div>
              )}
            </div>
            {fieldError("signature")}
          </div>

          {/* Agreement checkbox */}
          <label className={`flex items-start gap-3 cursor-pointer p-3 rounded-lg border transition-colors ${formData.agreed ? "bg-emerald-50 border-emerald-200" : errors.agreed ? "border-red-300 bg-red-50" : "border-navy-200"}`}>
            <input
              type="checkbox"
              checked={formData.agreed}
              onChange={(e) => { setFormData((p) => ({ ...p, agreed: e.target.checked })); if (errors.agreed) setErrors((p) => { const n = {...p}; delete n.agreed; return n; }); }}
              className="mt-1 h-4 w-4 rounded border-navy-300 text-navy-800 focus:ring-navy-500"
            />
            <span className="text-sm text-navy-600">
              I have read and agree to the terms of this Confidentiality and Non-Disclosure Agreement. 
              I understand this constitutes a legally binding agreement.
            </span>
          </label>
          {fieldError("agreed")}

          <Button type="submit" variant="gold" className="w-full active:scale-[0.98] transition-transform" size="lg" disabled={loading}>
            {loading ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Signing Agreement...
              </>
            ) : (
              <>
                <Shield className="mr-2 h-4 w-4" />
                Sign NDA & Access Deal
              </>
            )}
          </Button>

          <p className="text-xs text-navy-400 text-center">
            Your signature and IP address will be recorded for legal verification.
          </p>
        </CardContent>
      </Card>
    </form>
  );
}
