'use client';

import React, { useState, useEffect, useMemo } from 'react';
import { Header } from '../components/Header';
import { Footer } from '../components/Footer';
import api from '@/lib/api';

interface Province {
  id: number;
  name: string;
  name_fa?: string;
}

interface District {
  id: number;
  name: string;
  name_fa?: string;
  province_id: number;
}

interface Project {
  id: number;
  name: string;
  slug: string;
}

export default function CFRMPage() {
  const [formData, setFormData] = useState({
    name: '',
    father_name: '',
    job: '',
    province_id: '',
    district_id: '',
    village: '',
    phone_number: '',
    project_id: '',
    body: '',
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitStatus, setSubmitStatus] = useState<{
    type: 'success' | 'error' | null;
    message: string;
  }>({ type: null, message: '' });

  const [provinces, setProvinces] = useState<Province[]>([]);
  const [allDistricts, setAllDistricts] = useState<District[]>([]);
  const [projects, setProjects] = useState<Project[]>([]);
  const [loadingData, setLoadingData] = useState(true);

  const filteredDistricts = useMemo(() => {
    if (!formData.province_id) {
      return [];
    }
    return allDistricts.filter((district) => district.province_id === Number(formData.province_id));
  }, [formData.province_id, allDistricts]);

  useEffect(() => {
    const fetchData = async () => {
      setLoadingData(true);
      try {
        const [provincesData, districtsData, projectsData] = await Promise.all([
          api.getProvinces(),
          api.getDistricts(),
          api.getProjects({ status: 'active' }),
        ]);

        const provincesArray = Array.isArray(provincesData)
          ? provincesData
          : (provincesData as { data?: Province[] })?.data &&
              Array.isArray((provincesData as { data?: Province[] }).data)
            ? (provincesData as { data: Province[] }).data
            : [];

        const districtsArray = Array.isArray(districtsData)
          ? districtsData
          : (districtsData as { data?: District[] })?.data &&
              Array.isArray((districtsData as { data?: District[] }).data)
            ? (districtsData as { data: District[] }).data
            : [];

        const projectsArray = Array.isArray(projectsData)
          ? projectsData
          : (projectsData as { data?: Project[] })?.data &&
              Array.isArray((projectsData as { data?: Project[] }).data)
            ? (projectsData as { data: Project[] }).data
            : [];

        setProvinces(provincesArray);
        setAllDistricts(districtsArray);
        setProjects(projectsArray);
      } catch (error) {
        console.error('Error fetching data:', error);
        setProvinces([]);
        setAllDistricts([]);
        setProjects([]);
      } finally {
        setLoadingData(false);
      }
    };
    fetchData();
  }, []);

  useEffect(() => {
    if (!formData.province_id) {
      setFormData((prev) => ({ ...prev, district_id: '' }));
    }
  }, [formData.province_id]);

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>
  ) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setSubmitStatus({ type: null, message: '' });

    try {
      await api.submitCFRM({
        name: formData.name,
        father_name: formData.father_name || undefined,
        job: formData.job || undefined,
        province_id: formData.province_id ? Number(formData.province_id) : undefined,
        district_id: formData.district_id ? Number(formData.district_id) : undefined,
        village: formData.village || undefined,
        phone_number: formData.phone_number || undefined,
        project_id: formData.project_id ? Number(formData.project_id) : undefined,
        body: formData.body,
      });

      setSubmitStatus({
        type: 'success',
        message: 'Thank you for your submission. We will review and respond soon.',
      });

      setFormData({
        name: '',
        father_name: '',
        job: '',
        province_id: '',
        district_id: '',
        village: '',
        phone_number: '',
        project_id: '',
        body: '',
      });
    } catch (error: unknown) {
      setSubmitStatus({
        type: 'error',
        message: error instanceof Error ? error.message : 'Failed to submit form. Please try again.',
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const fieldClass =
    'w-full rounded-lg border border-secondary-300 bg-white px-4 py-3 text-sm outline-none transition-all focus:border-primary-500 focus:ring-2 focus:ring-primary-500/20 disabled:cursor-not-allowed disabled:bg-secondary-50';

  return (
    <div className="min-h-screen bg-white">
      <Header />

      <section className="relative overflow-hidden border-b border-secondary-200 bg-white pt-28 pb-12 sm:pt-32 sm:pb-16">
        <div className="pointer-events-none absolute -left-24 top-10 h-64 w-64 rounded-full bg-primary-500/10 blur-3xl" />
        <div className="pointer-events-none absolute -right-16 bottom-0 h-56 w-56 rounded-full bg-navy-800/5 blur-3xl" />

        <div className="relative mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
          <span className="inline-flex items-center gap-2 rounded-full border border-primary-500/30 bg-primary-500/10 px-4 py-1.5 text-xs font-bold uppercase tracking-widest text-primary-700">
            <span className="h-1.5 w-1.5 rounded-full bg-primary-500" />
            Accountability
          </span>

          <h1 className="mt-5 text-4xl font-black leading-tight text-neutral-900 sm:text-5xl md:text-6xl">
            Feedback &amp;{' '}
            <span className="relative inline-block text-primary-600">
              response
              <svg
                className="pointer-events-none absolute inset-x-0 top-full mt-1 h-2.5 w-full text-primary-400 sm:h-3"
                viewBox="0 0 80 12"
                preserveAspectRatio="none"
                aria-hidden
              >
                <path d="M2 9C22 2 58 2 78 9" stroke="currentColor" strokeWidth="4" strokeLinecap="round" fill="none" />
              </svg>
            </span>
          </h1>

          <p className="mt-6 max-w-2xl text-lg leading-relaxed text-neutral-600">
            Submit a complaint, feedback, or concern. We take every submission seriously and will
            respond promptly.
          </p>
        </div>
      </section>

      <section className="py-12 md:py-16">
        <div className="mx-auto grid max-w-7xl grid-cols-1 gap-8 px-4 sm:px-6 lg:grid-cols-12 lg:px-8">
          <div className="lg:col-span-4">
            <div className="rounded-2xl border border-secondary-200 bg-secondary-50 p-6 sm:p-8 lg:sticky lg:top-24">
              <h2 className="text-xl font-black text-neutral-900">Contact information</h2>
              <p className="mt-2 text-sm leading-relaxed text-neutral-600">
                Use these channels for complaints and feedback, or complete the form.
              </p>

              <ul className="mt-8 space-y-6">
                <li>
                  <p className="text-xs font-bold uppercase tracking-widest text-neutral-400">Email</p>
                  <a
                    href="mailto:complaints@sseoa.af"
                    className="mt-1 block font-semibold text-navy-800 hover:text-primary-600"
                  >
                    complaints@sseoa.af
                  </a>
                  <a
                    href="mailto:feedback@sseoa.af"
                    className="mt-1 block font-semibold text-navy-800 hover:text-primary-600"
                  >
                    feedback@sseoa.af
                  </a>
                </li>
                <li>
                  <p className="text-xs font-bold uppercase tracking-widest text-neutral-400">Phone</p>
                  <a
                    href="tel:0799303304"
                    className="mt-1 inline-block font-semibold text-navy-800 hover:text-primary-600"
                  >
                    0799 303 304
                  </a>
                </li>
                <li>
                  <p className="text-xs font-bold uppercase tracking-widest text-neutral-400">Address</p>
                  <address className="mt-1 not-italic font-semibold leading-relaxed text-neutral-800">
                    House #6, Street #7
                    <br />
                    Qala-e-Fatullah
                    <br />
                    Kabul, Afghanistan
                  </address>
                </li>
              </ul>
            </div>
          </div>

          <div className="lg:col-span-8">
            <div className="rounded-2xl border border-secondary-200 bg-white p-6 sm:p-8 md:p-10">
              <h2 className="text-2xl font-black text-neutral-900">Submit your feedback</h2>
              <p className="mt-2 text-sm text-neutral-600">
                Fill out the form below to share a complaint, concern, or suggestion.
              </p>

              {submitStatus.type && (
                <div
                  className={`mt-6 rounded-xl border px-4 py-3 text-sm font-medium ${
                    submitStatus.type === 'success'
                      ? 'border-emerald-200 bg-emerald-50 text-emerald-800'
                      : 'border-red-200 bg-red-50 text-red-800'
                  }`}
                >
                  {submitStatus.message}
                </div>
              )}

              {loadingData && (
                <div className="mt-6 rounded-xl border border-secondary-200 bg-secondary-50 px-4 py-3 text-sm text-neutral-700">
                  Loading form options…
                </div>
              )}

              <form onSubmit={handleSubmit} className="mt-8 space-y-5">
                <div className="grid grid-cols-1 gap-5 md:grid-cols-2">
                  <div>
                    <label htmlFor="name" className="mb-2 block text-sm font-semibold text-neutral-800">
                      Full name <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      id="name"
                      name="name"
                      required
                      value={formData.name}
                      onChange={handleChange}
                      className={fieldClass}
                      placeholder="Your full name"
                    />
                  </div>
                  <div>
                    <label htmlFor="father_name" className="mb-2 block text-sm font-semibold text-neutral-800">
                      Father name
                    </label>
                    <input
                      type="text"
                      id="father_name"
                      name="father_name"
                      value={formData.father_name}
                      onChange={handleChange}
                      className={fieldClass}
                      placeholder="Optional"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 gap-5 md:grid-cols-2">
                  <div>
                    <label htmlFor="job" className="mb-2 block text-sm font-semibold text-neutral-800">
                      Job / profession
                    </label>
                    <input
                      type="text"
                      id="job"
                      name="job"
                      value={formData.job}
                      onChange={handleChange}
                      className={fieldClass}
                      placeholder="Optional"
                    />
                  </div>
                  <div>
                    <label htmlFor="phone_number" className="mb-2 block text-sm font-semibold text-neutral-800">
                      Phone number
                    </label>
                    <input
                      type="tel"
                      id="phone_number"
                      name="phone_number"
                      value={formData.phone_number}
                      onChange={handleChange}
                      className={fieldClass}
                      placeholder="Optional"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 gap-5 md:grid-cols-3">
                  <div>
                    <label htmlFor="province_id" className="mb-2 block text-sm font-semibold text-neutral-800">
                      Province
                    </label>
                    <select
                      id="province_id"
                      name="province_id"
                      value={formData.province_id}
                      onChange={handleChange}
                      disabled={loadingData}
                      className={fieldClass}
                    >
                      <option value="">Select province</option>
                      {provinces.map((province) => (
                        <option key={province.id} value={province.id}>
                          {province.name_fa || province.name}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label htmlFor="district_id" className="mb-2 block text-sm font-semibold text-neutral-800">
                      District
                    </label>
                    <select
                      id="district_id"
                      name="district_id"
                      value={formData.district_id}
                      onChange={handleChange}
                      disabled={!formData.province_id || loadingData}
                      className={fieldClass}
                    >
                      <option value="">Select district</option>
                      {filteredDistricts.map((district) => (
                        <option key={district.id} value={district.id}>
                          {district.name_fa || district.name}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label htmlFor="village" className="mb-2 block text-sm font-semibold text-neutral-800">
                      Village
                    </label>
                    <input
                      type="text"
                      id="village"
                      name="village"
                      value={formData.village}
                      onChange={handleChange}
                      className={fieldClass}
                      placeholder="Optional"
                    />
                  </div>
                </div>

                <div>
                  <label htmlFor="project_id" className="mb-2 block text-sm font-semibold text-neutral-800">
                    Related project
                  </label>
                  <select
                    id="project_id"
                    name="project_id"
                    value={formData.project_id}
                    onChange={handleChange}
                    disabled={loadingData}
                    className={fieldClass}
                  >
                    <option value="">Select project (optional)</option>
                    {projects.map((project) => (
                      <option key={project.id} value={project.id}>
                        {project.name}
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <label htmlFor="body" className="mb-2 block text-sm font-semibold text-neutral-800">
                    Message <span className="text-red-500">*</span>
                  </label>
                  <textarea
                    id="body"
                    name="body"
                    required
                    rows={6}
                    maxLength={10000}
                    value={formData.body}
                    onChange={handleChange}
                    className={`${fieldClass} resize-none`}
                    placeholder="Describe your complaint, feedback, or concern"
                  />
                  <p className="mt-1 text-xs text-neutral-400">{formData.body.length}/10000</p>
                </div>

                <button
                  type="submit"
                  disabled={isSubmitting || loadingData}
                  className="inline-flex cursor-pointer items-center justify-center rounded-lg bg-navy-800 px-6 py-3 text-sm font-bold text-white transition-colors hover:bg-navy-700 disabled:cursor-wait disabled:opacity-60"
                >
                  {isSubmitting ? 'Sending…' : 'Submit feedback'}
                </button>
              </form>
            </div>
          </div>
        </div>
      </section>

      <Footer />
    </div>
  );
}
